<?php
namespace YMApi\Controller;
use Think\Controller;
use Think\Model;

class AppController extends Controller {
	private $appkey='key4token';
	private $expiration_time=7200;//单位 /秒
	private $apptime='';
	private $apptoken='';
	public $uid;
	public $open_id;
	public $session_table = '';
	public $max_life_time = 1800;
	public $session_name = '';
	public $session_id = '';
	public $session_expiry = '';
	public $session_md5 = '';
	public  $session_cookie_path = '/';
	public  $session_cookie_domain = '';
	public $session_cookie_secure = false;
	public $_ip = '';
	public  $_time = 0;
	public $check_uid=FALSE;
	public $is_hd = 0; //是否为HD请求；
	
	protected function _initialize($apptoken='',$apptime='',$check_uid=false,$session_id='',$check_sign=true,$set_action=true) {
		header("Access-Control-Allow-Origin: *");
		$this->apptoken=$_REQUEST['mac'];
		$this->apptime=$_REQUEST['time'];
//        $is_store = I('post.store');
		$ationarr=array('batch_warehouse_request','auto_order_cancel','system_pandian');
        if(!$set_action && in_array(ACTION_NAME, $ationarr)){
           //不验证的方法
        }else{
//            if($is_store!=1){
                $this->_checkAppToken($check_sign);
//            }
        }
//		$GLOBALS['_SESSION'] = array();
//
//		if (!empty($GLOBALS['cookie_path'])) {
//		    $this->session_cookie_path = $GLOBALS['cookie_path'];
//		} else {
//		    $this->session_cookie_path = '/';
//		}
//
//		if (!empty($GLOBALS['cookie_domain'])) {
//		    $this->session_cookie_domain = $GLOBALS['cookie_domain'];
//		} else {
//		    $this->session_cookie_domain = '';
//		}
//
//		if (!empty($GLOBALS['cookie_secure'])) {
//		    $this->session_cookie_secure = $GLOBALS['cookie_secure'];
//		} else {
//		    $this->session_cookie_secure = false;
//		}
//
//		$this->session_name = C('COOKIE_PREFIX').'touch_id';
//		$this->session_table = M('sessions');
//		$this->session_data_table = M('sessions_data');
		
		$this->_ip = get_client_ip();
		
		if($check_uid || $this->check_uid){ 
		    $this->check_uid();	//验证UID 是否存在
//		    if ($session_id == '' && !empty($_COOKIE[$this->session_name])) {
//		        $this->session_id = $_COOKIE[$this->session_name];
//		    } else {
//		        $this->session_id = $session_id;
//		    }
//
//
//		    if ($this->session_id) {
//		        $tmp_session_id = substr($this->session_id, 0, 32);
//		        if ($this->gen_session_key($tmp_session_id) == substr($this->session_id, 32)) {
//		            $this->session_id = $tmp_session_id;
//		        } else {
//		            $this->session_id = '';
//		        }
//		    }
//
//		    $this->_time = time();
//
//		    if ($this->session_id) {
//		        $this->load_session();
//		    } else {
//		        $this->session_id=$this->get_session_id();
//		        if(empty($this->session_id)){
//		            $this->get_session_uid_info($this->uid);
//		        }
//		        setcookie($this->session_name, $this->session_id . $this->gen_session_key($this->session_id), 0, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);
//		    }
		    define('SESS_ID', '');
		    define( 'UID', $this->uid );
		    define( 'IS_HD', $this->is_hd );
//		    register_shutdown_function($this->close_session());
		}
	}
		
		// 验证Token
	protected function _checkAppToken($check_sign){
		//判断token方式 新版或者旧版
		if($check_sign){
			if(strlen($_REQUEST['sign'])>10){
				//按照H5处理
				$data['uid'] = I("post.uid");	//uid
				$data['sgin'] = $_REQUEST['sign'];	//sign
				$Write = M("user_token")->where($data)->count();
				if($Write==0){
					returnApiError("sign 过期，请重新登录");
				}
			}else{
				$checkdata=apiencryption($this->apptoken,$this->appkey,$this->apptime,$this->expiration_time);
				if($checkdata){
					if($checkdata===2){
						returnApiError('请求参数错误！');
					}
				}else{
					returnApiError('请求已过期');
				}
			}
		}else{
			$checkdata=apiencryption($this->apptoken,$this->appkey,$this->apptime,$this->expiration_time);
			if($checkdata){
				if($checkdata===2){
					returnApiError('请求参数错误！');
				}
			}else{
				returnApiError('请求已过期');
			}
		}


	}


	protected function check_uid() {
		$this->uid=I("post.uid");
		$this->open_id=I("post.openid");
		$this->is_hd = I("post.IS_HD", 0, "intval");
		if(empty($this->uid)){
			returnApiError("uid is null");
		}else{
		    $this->check_uid=true;
//		    $this->get_session_uid_info($this->uid);
		    return true;
		}
	}
	
	protected function gen_session_id() {
	    $this->session_id = md5(uniqid(mt_rand(), true));
	
	    return $this->insert_session();
	}
	
	protected function gen_session_key($session_id) {
	    static $ip = '';
	
	    if ($ip == '') {
	        $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));
	    }
	
	    return sprintf('%08x', crc32(ROOT_PATH . $ip . $session_id));
	}
	
	protected function insert_session() {
	    $data=array(
	        'sesskey'=>$this->session_id,
	        'expiry'=>$this->_time,
	        'ip'=>$this->_ip,
	        'data'=>'a:0:{}'
	    );
	    return $this->session_table->add($data);
	    //return $this->db->query('INSERT INTO ' . $this->session_table . " (sesskey, expiry, ip, data) VALUES ('" . $this->session_id . "', '" . $this->_time . "', '" . $this->_ip . "', 'a:0:{}')");
	}
	
	protected function load_session() {
	    //$session = $this->db->getRow('SELECT userid, adminid, user_name, user_rank, discount, email, data, expiry FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "'");
	    $session =$this->session_table->field('userid, adminid, user_name, user_rank, discount, email, data, expiry')
	               ->where(array('sesskey'=>$this->session_id))
	               ->find(); 
	    if (empty($session)) {
	        $this->insert_session();
	        $this->session_expiry = 0;
	        $this->session_md5 = '40cd750bba9870f18aada2478b24840a';
	        $GLOBALS['_SESSION'] = array();
	    } else {
	        if (!empty($session['data']) && $this->_time - $session['expiry'] <= $this->max_life_time) {
	            $this->session_expiry = $session['expiry'];
	            $this->session_md5 = md5($session['data']);
	            $GLOBALS['_SESSION'] = unserialize($session['data']);
	            $GLOBALS['_SESSION']['user_id'] = $session['userid'];
	            $GLOBALS['_SESSION']['admin_id'] = $session['adminid'];
	            $GLOBALS['_SESSION']['user_name'] = $session['user_name'];
	            $GLOBALS['_SESSION']['user_rank'] = $session['user_rank'];
	            $GLOBALS['_SESSION']['discount'] = $session['discount'];
	            $GLOBALS['_SESSION']['email'] = $session['email'];
	        } else {
	           // $session_data = $this->db->getRow('SELECT data, expiry FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "'");
	            $session_data=$this->session_data_table->field('data, expiry')->where(array('sesskey'=>$this->session_id))->find();
	            if (!empty($session_data['data']) && $this->_time - $session_data['expiry'] <= $this->max_life_time) {
	                $this->session_expiry = $session_data['expiry'];
	                $this->session_md5 = md5($session_data['data']);
	                $GLOBALS['_SESSION'] = unserialize($session_data['data']);
	                $GLOBALS['_SESSION']['user_id'] = $session['userid'];
	                $GLOBALS['_SESSION']['admin_id'] = $session['adminid'];
	                $GLOBALS['_SESSION']['user_name'] = $session['user_name'];
	                $GLOBALS['_SESSION']['user_rank'] = $session['user_rank'];
	                $GLOBALS['_SESSION']['discount'] = $session['discount'];
	                $GLOBALS['_SESSION']['email'] = $session['email'];
	            } else {
	                $this->session_expiry = 0;
	                $this->session_md5 = '40cd750bba9870f18aada2478b24840a';
	                $GLOBALS['_SESSION'] = array();
	            }
	        }
	    }
	}
	
	protected function update_session() {
	    $adminid = !empty($GLOBALS['_SESSION']['admin_id']) ? intval($GLOBALS['_SESSION']['admin_id']) : 0;
        $userid = !empty($GLOBALS['_SESSION']['user_id']) ? intval($GLOBALS['_SESSION']['user_id']) : 0;
        $user_name = !empty($GLOBALS['_SESSION']['user_name']) ? trim($GLOBALS['_SESSION']['user_name']) : 0;
        $user_rank = !empty($GLOBALS['_SESSION']['user_rank']) ? intval($GLOBALS['_SESSION']['user_rank']) : 0;
        $discount = !empty($GLOBALS['_SESSION']['discount']) ? round($GLOBALS['_SESSION']['discount'], 2) : 0;
        $email = !empty($GLOBALS['_SESSION']['email']) ? trim($GLOBALS['_SESSION']['email']) : 0;
	    /*unset($GLOBALS['_SESSION']['admin_id']);
	    unset($GLOBALS['_SESSION']['user_id']);
	    unset($GLOBALS['_SESSION']['user_name']);
	    unset($GLOBALS['_SESSION']['user_rank']);
	    unset($GLOBALS['_SESSION']['discount']);
	    unset($GLOBALS['_SESSION']['email']);*/
	
	    $data = serialize($GLOBALS['_SESSION']);
	    $this->_time = time();
	
	    if ($this->session_md5 == md5($data) && $this->_time < $this->session_expiry + 10) {
	        return true;
	    }
	    
	    
	   // $data = addslashes($data);
	    
	    /*if (isset($data{255})) {
	        $this->autoReplace('sessions_data', array('sesskey' => $this->session_id, 'expiry' => $this->_time, 'data' => $data), array('expiry' => $this->_time, 'data' => $data));
	        $data = '';
	    }*/
	    $savedata=array(
	        'expiry'=>$this->_time,
	        'ip'=>$this->_ip,
	        'userid'=>$userid,
	        'adminid'=>$adminid,
	        'user_name'=>$user_name,
	        'user_rank'=>$user_rank,
	        'discount'=>$discount,
	        'email'=>$email,
	        'data'=>$data,
	    );
	    return $this->session_table->where(array('sesskey'=>$this->session_id))->save($savedata);
	    //return $this->db->query('UPDATE ' . $this->session_table . " SET expiry = '" . $this->_time . "', ip = '" . $this->_ip . "', userid = '" . $userid . "', adminid = '" . $adminid . "', user_name='" . $user_name . "', user_rank='" . $user_rank . "', discount='" . $discount . "', email='" . $email . "', data = '$data' WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
	}
	
	protected function close_session() {
	    $this->update_session();
	    if (mt_rand(0, 2) == 2) {
	        $where['expiry']=array('LT',$this->_time - $this->max_life_time);
	        $this->session_data_table->where($where)->delete();
	        //$this->db->query('DELETE FROM ' . $this->session_data_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time));
	    }
	
	    if ((time() % 2) == 0) {
	        $where['expiry']=array('LT',$this->_time - $this->max_life_time);
	        return $this->session_table->where($where)->delete();
	        //return $this->db->query('DELETE FROM ' . $this->session_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time));
	    }
	
// 	    w_log("cyb", $this->uid.'_'.time());
	    
	    return true;
	}
	
	protected function delete_spec_admin_session($adminid) {
	    if (!empty($GLOBALS['_SESSION']['admin_id']) && $adminid) {
	        return $this->session_table->where(array('adminid'=>$adminid))->delete();
	        //return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE adminid = '$adminid'");
	    } else {
	        return false;
	    }
	}
	
	protected function destroy_session() {
	    $GLOBALS['_SESSION'] = array();
	
	    setcookie($this->session_name, $this->session_id, 1, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);
	
	   
	    if (!empty($GLOBALS['ecs'])) {
// 	        M('cart')->where(array('session_id'=>$this->session_id))->delete();
	        //$this->db->query('DELETE FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '$this->session_id'");
	    }
	    
	    $this->session_data_table->where(array('sesskey'=>$this->session_id))->delete();
	    return $this->session_table->where(array('sesskey'=>$this->session_id))->delete();
	    //return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
	}
	
	protected function get_session_id() {
	    return $this->session_id;
	}
	
	protected function get_users_count() {
	    return $this->session_table->count();
	    //return $this->db->getOne('SELECT count(*) FROM ' . $this->session_table);
	}
	
	
   protected function get_session_uid_info($uid){
       $session=$this->session_table->where(array('userid'=>$uid))->find();
       if($session){
           $this->session_id=$session['sesskey'];
//           $this->load_session();
           return true;
       }else{
//           $this->gen_session_id();
           return false;
       }
   }
	
	protected function autoReplace($table, $field_values, $update_values, $where = '', $querymode = '') {
	    $table_mod=M($table);
	    $row=$table_mod->select();
	    foreach ($row as $k=>$v){
	        $field_descs[] = $v;
	    }
	    if (!is_array($field_descs)) {
	        $field_descs = array();
	    }
	    $primary_keys = array();
	    foreach ($field_descs AS $value) {
	        $field_names[] = $value['Field'];
	        if ($value['Key'] == 'PRI') {
	            $primary_keys[] = $value['Field'];
	        }
	    }
	
	    $fields = $values = array();
	    foreach ($field_names AS $value) {
	        if (array_key_exists($value, $field_values) == true) {
	            $fields[] = $value;
	            $values[] = "'" . $field_values[$value] . "'";
	        }
	    }
	
	    $sets = array();
	    foreach ($update_values AS $key => $value) {
	        if (array_key_exists($key, $field_values) == true) {
	            if (is_int($value) || is_float($value)) {
	                $sets[] = $key . ' = ' . $key . ' + ' . $value;
	            } else {
	                $sets[] = $key . " = '" . $value . "'";
	            }
	        }
	    }
	
	    $sql = '';
	    if (empty($primary_keys)) {
	        if (!empty($fields)) {
	            $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
	        }
	    } else {
	        if (mysql_get_server_info() >= '4.1') {
	            if (!empty($fields)) {
	                $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
	                if (!empty($sets)) {
	                    $sql .= 'ON DUPLICATE KEY UPDATE ' . implode(', ', $sets);
	                }
	            }
	        } else {
	            if (empty($where)) {
	                $where = array();
	                foreach ($primary_keys AS $value) {
	                    if (is_numeric($value)) {
	                        $where[] = $value . ' = ' . $field_values[$value];
	                    } else {
	                        $where[] = $value . " = '" . $field_values[$value] . "'";
	                    }
	                }
	                $where = implode(' AND ', $where);
	            }
	
	            if ($where && (!empty($sets) || !empty($fields))) {
	                
	                if (intval($table_mod->where($where)->count()) > 0) {
	                    if (!empty($sets)) {
	                        $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
	                    }
	                } else {
	                    if (!empty($fields)) {
	                        $sql = 'REPLACE INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
	                    }
	                }
	            }
	        }
	    }
	    if ($sql) {
	        return $table_mod->query($sql, $querymode);
	    } else {
	        return false;
	    }  
	}
	
	protected  function check_session(){
	    if(empty($GLOBALS['_SESSION']['user_id'])){
	        returnApiError('session not null');
	    }
	}
	
}